<?php
/**
 * Created by PhpStorm.
 * User: JYuans
 * Date: 2019/12/5
 * Time: 9:10
 */
namespace Bstage\Controller;

use Common\Model\CommonModel;

class MidExamineResultController extends BstageController {

    /**
     * 获取最终考核权重列表
     */
    public function getWeightList(){
        //必要参数
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");

        $examine_item_count = M("MidExamineItem")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->count();
        if(!$examine_item_count){
            $this->errorReturn("中层考核ID错误");
        }

        //分页
        $now_page = $_REQUEST['now_page']?$_REQUEST['now_page']:1;//默认第一页
        $page_size = $_REQUEST['page_size']?$_REQUEST['page_size']:50;//默认每页50条

        //查询条件
        $where = array();
        //筛选中层员工
        if($_REQUEST["search_user_id"]){
            $where['user_id'] = $_REQUEST["search_user_id"];
        }
        //筛选级别
        if($_REQUEST["search_rank"] == 3 || $_REQUEST["search_rank"] == 4){
            $where['rank'] = $_REQUEST["search_rank"];
        }else{
            $where['rank'] = ['in','3,4'];
        }
        //筛选干部名称
        if($_REQUEST["search_name"]){
            $where['name'] = ['like','%'.$_REQUEST['search_name'].'%'];
        }
        //筛选职务
        if($_REQUEST["search_station"]){
            $where['station'] = ['like','%'.$_REQUEST['search_station'].'%'];
        }

        $field = "user_id,depart_id,number,name,rank,station,station_type";

        $list_data = M("User")
            ->where($where)
            ->page($now_page,$page_size)
            ->order("user_id")
            ->field($field)
            ->select();

        if(!$list_data){
            $this->returnJson(503,"无数据");
        }

        $depart_id_array = array_column($list_data,"depart_id");
        $depart_name_array = M("Department")
            ->where(['depart_id'=>['in',$depart_id_array]])
            ->getField("depart_id,name");

        $final_result_user_data = M("MidExamineResult")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->getField("be_examine_user_id,up_weight,same_weight,down_weight,manage_score,full_manage_score,result_type");
        if(!$final_result_user_data){
            $final_result_user_data = array();
        }

        foreach($list_data as $key=>$value){
            $list_data[$key]['depart_name'] = $depart_name_array[$value['depart_id']];
            $list_data[$key]['rank'] = CommonModel::rank_str_array[$value['rank']];

            if(isset($final_result_user_data[$value['user_id']])){
                $list_data[$key]['down_weight'] = bcmul($final_result_user_data[$value['user_id']]['down_weight'],100);
                $list_data[$key]['same_weight'] = bcmul($final_result_user_data[$value['user_id']]['same_weight'],100);
                $list_data[$key]['up_weight'] = bcmul($final_result_user_data[$value['user_id']]['up_weight'],100);
                $list_data[$key]['manage_score'] = $final_result_user_data[$value['user_id']]['manage_score'];
                $list_data[$key]['full_manage_score'] = $final_result_user_data[$value['user_id']]['full_manage_score'];
                $list_data[$key]['result_type'] = $final_result_user_data[$value['user_id']]['result_type'];
            }else{
                $list_data[$key]['down_weight'] = 0;
                $list_data[$key]['same_weight'] = 0;
                $list_data[$key]['up_weight'] = 0;
                $list_data[$key]['manage_score'] = 0;
                $list_data[$key]['full_manage_score'] = 0;
                $list_data[$key]['result_type'] = "";
            }
        }

        $count = M("User")
            ->where($where)
            ->count();

        $return_data = array();
        $return_data['list_data'] = $list_data;
        $return_data['count'] = $count;
        $return_data['now_page'] = $now_page;
        $return_data['page_size'] = $page_size;
        $return_data['max_page'] = ceil($count / $page_size);

        $this->successReturn("获取成功",$return_data);
    }

    /**
     * 设置考核权重接口
     */
    public function setWeightAction(){
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");

        $check_examine_status = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("status")
            ->find();
        if(!$check_examine_status){
            $this->errorReturn("中层考核ID错误，请重新尝试");
        }

        $user_id = $_REQUEST['user_id']?$_REQUEST['user_id']:$this->errorReturn("缺少中层人员ID");

        $new_data = array();
        $new_data['up_weight'] = is_numeric($_REQUEST['up_weight'])&&$_REQUEST['up_weight']>=0?bcdiv($_REQUEST['up_weight'],100,2):$this->errorReturn("请输入上级考评权重");
        $new_data['same_weight'] = is_numeric($_REQUEST['same_weight'])&&$_REQUEST['same_weight']>=0?bcdiv($_REQUEST['same_weight'],100,2):$this->errorReturn("请输入中级考评权重");
        $new_data['down_weight'] = is_numeric($_REQUEST['down_weight'])&&$_REQUEST['down_weight']>=0?bcdiv($_REQUEST['down_weight'],100,2):$this->errorReturn("请输入下级考评权重");

        $new_data['manage_score'] = $_REQUEST['manage_score']?$_REQUEST['manage_score']:0;
        $new_data['full_manage_score'] = $_REQUEST['full_manage_score']?$_REQUEST['full_manage_score']:0;

        $new_data['result_type'] = $_REQUEST['result_type']?$_REQUEST['result_type']:"";

        $amount_weight = bcadd(bcadd($new_data['up_weight'],$new_data['same_weight'],2),$new_data['down_weight'],2);
        if($amount_weight != 1){
            $this->errorReturn("权重和必须等于100");
        }

        $check_result_data = M("MidExamineResult")
            ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id])
            ->count();
        if($check_result_data){
            $update_result = M("MidExamineResult")
                ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id])
                ->save($new_data);
        }else{
            $user_data = M("User")
                ->where(['user_id'=>$user_id])
                ->find();
            $new_data['mid_ex_id'] = $mid_ex_id;
            $new_data['be_examine_user_id'] = $user_id;
            $new_data['depart_id'] = $user_data['depart_id'];
            $new_data['number'] = $user_data['number'];
            $new_data['name'] = $user_data['name'];
            $new_data['rank'] = $user_data['rank'];
            $new_data['station'] = $user_data['station'];
            $new_data['station_type'] = $user_data['station_type'];

            $update_result = M("MidExamineResult")
                ->add($new_data);
        }
        if($update_result){
            $this->successReturn("修改成功");
        }else{
            $this->errorReturn("修改失败，请重新尝试");
        }
    }

    /**
     * 批量设置权重接口
     */
    public function batchSetWeightAction(){
        $mid_ex_id = $_REQUEST['mid_ex_id']?$_REQUEST['mid_ex_id']:$this->errorReturn("缺少中层考核ID");

        $check_examine_status = M("MidExamine")
            ->where(['mid_ex_id'=>$mid_ex_id])
            ->field("status")
            ->find();
        if(!$check_examine_status){
            $this->errorReturn("中层考核ID错误，请重新尝试");
        }
        $file_type = strrchr($_FILES['csv_file']['name'],".");

        if(!$_FILES['csv_file']){
            $this->errorReturn("请上传csv文件");
        }

        if($file_type == ".xlsx" || $file_type == ".xls"){
            Vendor('PHPExcel.PHPExcel');
            Vendor('PHPExcel.PHPExcel.IOFactory');
            Vendor('PHPExcel.PHPExcel.Reader.Excel5');
            Vendor('PHPExcel.PHPExcel.Reader.Excel2007');
            //以上三步加载phpExcel的类
            $filename = $_FILES['csv_file']['tmp_name'];

            if ($file_type =='.xlsx') {
                $objReader = new \PHPExcel_Reader_Excel2007();
                $objExcel = $objReader ->load($filename);
            } else if ($file_type =='.xls') {
                $objReader = new \PHPExcel_Reader_Excel5();
                $objExcel = $objReader ->load($filename);
            }
            $sheet = $objExcel ->getSheet(0);
            $highestRow = $sheet->getHighestRow(); // 取得总行数
            // $highestColumn = $sheet->getHighestColumn(); // 取得总列数

            //循环读取excel表格,读取一条,插入一条
            //j表示从哪一行开始读取  从第二行开始读取，因为第一行是标题不保存
            //$a表示列号
            $model = M();
            $model->startTrans();

            $user_id_not_find_number = "";
            $is_not_same_user = "";
            for($j=2;$j<=$highestRow;$j++) {
                $number = $objExcel->getActiveSheet()->getCell("A".$j)->getValue();
                $up_weight = $objExcel->getActiveSheet()->getCell("F".$j)->getValue();
                $same_weight = $objExcel->getActiveSheet()->getCell("G".$j)->getValue();
                $down_weight = $objExcel->getActiveSheet()->getCell("H".$j)->getValue();
                $manage_score = $objExcel->getActiveSheet()->getCell("I".$j)->getValue();
                $full_manage_score = $objExcel->getActiveSheet()->getCell("J".$j)->getValue();
                $result_type = $objExcel->getActiveSheet()->getCell("K".$j)->getValue();

                $check_user_number = M("User")
                    ->where(['number'=>$number])
                    ->field("user_id,rank")
                    ->find();
                if(!$check_user_number){
                    $user_id_not_find_number .= $number.",";
                    continue;
                }
                if($check_user_number['rank'] != 3 && $check_user_number['rank'] != 4){
                    $is_not_same_user .= $number.",";
                    continue;
                }
                $user_id = $check_user_number['user_id'];
                $new_data = array();
                $new_data['up_weight'] = is_numeric($up_weight)&&$up_weight>=0?bcdiv($up_weight,100,2):0;
                $new_data['same_weight'] = is_numeric($same_weight)&&$same_weight>=0?bcdiv($same_weight,100,2):0;
                $new_data['down_weight'] = is_numeric($down_weight)&&$down_weight>=0?bcdiv($down_weight,100,2):0;

                $new_data['manage_score'] = $manage_score?$manage_score:0;
                $new_data['full_manage_score'] = $full_manage_score?$full_manage_score:0;
                $new_data['result_type'] = $result_type?$result_type:"";

                $amount_weight = bcadd(bcadd($new_data['up_weight'],$new_data['same_weight'],2),$new_data['down_weight'],2);
                if($amount_weight != 1){
                    $model->rollback();
                    $this->errorReturn("工号：".$number."，权重和必须等于100");
                }

                $check_result_data = M("MidExamineResult")
                    ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id])
                    ->count();
                if($check_result_data){
                    $new_data['update_time'] = time();
                    M("MidExamineResult")
                        ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id])
                        ->save($new_data);
                    $update_result = true;
                }else{
                    $user_data = M("User")
                        ->where(['user_id'=>$user_id])
                        ->find();
                    $new_data['mid_ex_id'] = $mid_ex_id;
                    $new_data['be_examine_user_id'] = $user_id;
                    $new_data['depart_id'] = $user_data['depart_id'];
                    $new_data['number'] = $user_data['number'];
                    $new_data['name'] = $user_data['name'];
                    $new_data['rank'] = $user_data['rank'];
                    $new_data['station'] = $user_data['station'];
                    $new_data['station_type'] = $user_data['station_type'];

                    $update_result = M("MidExamineResult")
                        ->add($new_data);
                }
                if(!$update_result){
                    $model->rollback();
                    $this->errorReturn("添加权重数据失败，请重新尝试");
                }
            }
            $model->commit();
            $return_message = "导入成功";
            if($user_id_not_find_number){
                $return_message .= "；未找到工号：".$user_id_not_find_number;
            }
            if($is_not_same_user){
                $return_message .= "；非中层人员工号：".$is_not_same_user;
            }
        }else if($file_type == ".csv"){
            //打开文件
            $file = fopen($_FILES['csv_file']['tmp_name'],"r");
            //读取第一行数据
            $line = fgetcsv($file);
            //判断第一行是否为10列
            //addFileLog("列数：".json_encode($line));
            if(count($line) != 11){
                fclose($file);
                $this->errorReturn("文件格式错误：导入文件列数必须为10列");
            }
            //判断第一列标题是否为工号
            if(iconv('gb2312','utf-8',$line[0]) != "工号"){
                fclose($file);
                $this->errorReturn("文件格式错误：文件第一列标题必须为“工号”");
            }

            $model = M();
            $model->startTrans();

            $user_id_not_find_number = "";
            $is_not_same_user = "";
            while($line = fgetcsv($file)){

                $check_user_number = M("User")
                    ->where(['number'=>$line[0]])
                    ->field("user_id,rank")
                    ->find();
                if(!$check_user_number){
                    $user_id_not_find_number .= $line[0].",";
                    continue;
                }
                if($check_user_number['rank'] != 3 && $check_user_number['rank'] != 4){
                    $is_not_same_user .= $line[0].",";
                    continue;
                }
                $user_id = $check_user_number['user_id'];
                $new_data = array();
                $new_data['up_weight'] = is_numeric($line[5])&&$line[5]>=0?bcdiv($line[5],100,2):0;
                $new_data['same_weight'] = is_numeric($line[6])&&$line[6]>=0?bcdiv($line[6],100,2):0;
                $new_data['down_weight'] = is_numeric($line[7])&&$line[7]>=0?bcdiv($line[7],100,2):0;

                $new_data['manage_score'] = $line[8]?$line[8]:0;
                $new_data['full_manage_score'] = $line[9]?$line[9]:0;
                $new_data['result_type'] = $line[10]?$line[10]:0;

                $amount_weight = bcadd(bcadd($new_data['up_weight'],$new_data['same_weight'],2),$new_data['down_weight'],2);
                if($amount_weight != 1){
                    fclose($file);
                    $model->rollback();
                    $this->errorReturn("工号：".$line[0]."，权重和必须等于100");
                }

                $check_result_data = M("MidExamineResult")
                    ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id])
                    ->count();
                if($check_result_data){
                    $new_data['update_time'] = time();
                    M("MidExamineResult")
                        ->where(['mid_ex_id'=>$mid_ex_id,'be_examine_user_id'=>$user_id])
                        ->save($new_data);
                    $update_result = true;
                }else{
                    $user_data = M("User")
                        ->where(['user_id'=>$user_id])
                        ->find();
                    $new_data['mid_ex_id'] = $mid_ex_id;
                    $new_data['be_examine_user_id'] = $user_id;
                    $new_data['depart_id'] = $user_data['depart_id'];
                    $new_data['number'] = $user_data['number'];
                    $new_data['name'] = $user_data['name'];
                    $new_data['rank'] = $user_data['rank'];
                    $new_data['station'] = $user_data['station'];
                    $new_data['station_type'] = $user_data['station_type'];

                    $update_result = M("MidExamineResult")
                        ->add($new_data);
                }
                if(!$update_result){
                    fclose($file);
                    $model->rollback();
                    $this->errorReturn("添加权重数据失败，请重新尝试");
                }
                /*for($i=0;$i<count($line);$i++){
                    print_r(iconv('gb2312','utf-8',$line[$i]));
                }*/
            }
            fclose($file);
            $model->commit();
            $return_message = "导入成功";
            if($user_id_not_find_number){
                $return_message .= "；未找到工号：".$user_id_not_find_number;
            }
            if($is_not_same_user){
                $return_message .= "；非中层人员工号：".$is_not_same_user;
            }
        }else{
            $this->errorReturn("文件必须为xls，xlsx，csv文件");
        }
        $this->successReturn($return_message);
    }
}